import IconArrowLeft from '@/assets/svg/icon_arrow_left'
import IconArrowRight from '@/assets/svg/icon_arrow_right'
import React, { memo, useEffect, useRef, useState } from 'react'
import { ScrollWrapper } from './style'

const ScrollView = memo((props) => {
  const [isShowRight, setIsShowRight] = useState(false)
  const [isShowLeft, setIsShowLeft] = useState(false)
  const [posIndex, setPosIndex] = useState(0)
  const escessRef = useRef()
  const newIndexRef = useRef()

  const scrollContentRef = useRef()
  useEffect(() => {
    const offsetWidth = scrollContentRef.current.offsetWidth
    const scrollWidth = scrollContentRef.current.scrollWidth
    const escess = scrollWidth - offsetWidth
    escessRef.current = escess
    setIsShowRight(escess > 0)
  }, [props.children])

  function arrowsHandleClick (isLeft) {
    newIndexRef.current = isLeft ? posIndex - 1 : posIndex + 1
    const newEl = scrollContentRef.current.children[newIndexRef.current]
    const newOffsetLeft = newEl.offsetLeft
    scrollContentRef.current.style.transform = `translate(-${newOffsetLeft}px)`
    setPosIndex(newIndexRef.current)
    // 设置右边按钮是否显示
    setIsShowRight(escessRef.current > newOffsetLeft)
    setIsShowLeft(newOffsetLeft > 0)
  }

  return (
    <ScrollWrapper>
      {isShowLeft && (
        <div className="left-arrow" onClick={e => arrowsHandleClick(true)}>
          <IconArrowLeft />
        </div>
      )}
      {isShowRight && (
        <div className="right-arrow" onClick={e => arrowsHandleClick(false)}>
          <IconArrowRight />
        </div>
      )}

      <div className="scroll-content">
        <div className="slot" ref={scrollContentRef}>
          {props.children}
        </div>
      </div>
    </ScrollWrapper>
  )
})

export default ScrollView